package com.mes.cloud.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.Map;

/**
 * Created by Lenovo on 2017/7/20.
 */
public class HttpUtils {
    public static HttpEntity<?> getHttpEntity(MediaType mediaType, Map<String, String> handerMap,Object obj) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);

        if (handerMap != null) {
            for (Map.Entry<String, String> entry : handerMap.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<?> entity = new HttpEntity(obj,headers);
        return entity;
    }

    public static HttpEntity<?> getHttpEntity(MediaType mediaType, Map<String, String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);

        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<?> entity = new HttpEntity(headers);
        return entity;
    }

    public static HttpEntity<?> getHttpEntity(Map<String, String> map) {
        HttpHeaders headers = new HttpHeaders();

        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<?> entity = new HttpEntity(headers);
        return entity;
    }

    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer strb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            strb.append(entry.getKey() + "=" + entry.getValue());
            strb.append("&");
        }
        String urlParams = strb.toString();
        if (urlParams.endsWith("&")) {
            urlParams = StringUtils.substringBeforeLast(urlParams, "&");
        }
        return urlParams;
    }
}
